<?php

namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use ModelTree, AdminBuilder;

    protected $table = 'gov_categories';

    /**
     * 重写下拉框数据显示
     *
     * @param \Closure|null $closure
     * @param string $rootText
     * @param bool $flag
     * @return array
     */
    public static function selectOptions(\Closure $closure = null, $rootText = '根目录', $flag = true)
    {
        $options = (new static())->withQuery($closure)->buildSelectOptions();

        if ($flag)
            return collect($options)->prepend($rootText, 0)->all();
        else
            return collect($options)->all();

    }

    /**
     * 获取所有父类
     *
     * @param $pid
     * @return array
     */
    public static function getParentCat($pid)
    {
        static $cat_row = [];
        $cat = Category::find($pid)->toArray();
        $cat_row[] = $cat;
        if ($cat['parent_id']) {
            static::getParentCat($cat['parent_id']);
        }

        return $cat_row;
    }

    /**
     * 获取所有子类
     *
     * @param int $parent_id
     * @param bool $recursive
     * @return array
     */
    public function getCatChild($parent_id = 0, $recursive = true)
    {
        if (is_array($parent_id)){
            $res = static::whereIn('parent_id', $parent_id)->select(['id', 'title'])->get()->toArray();
        } else {
            $res = static::where('parent_id', $parent_id)->select(['id', 'title'])->get()->toArray();
        }

        if ($recursive && $res){
            $cat_id_row = array_column($res, 'id');
            $rs = call_user_func_array(array($this,'getCatChild'), array($cat_id_row, $recursive));
            $res = array_merge($res, $rs);
        }

        return $res;
    }

    /**
     * 获取所有子类的id
     *
     * @param int $parent_id
     * @param bool $recursive
     * @return array
     */
    public function getCatChildId($parent_id = 0, $recursive = true)
    {
        if (is_array($parent_id)){
            $res = static::whereIn('parent_id', $parent_id)->select(['id'])->get()->toArray();
        } else {
            $res = static::where('parent_id', $parent_id)->select(['id'])->get()->toArray();
        }

        $cat_id_row = array_column($res, 'id');

        if ($recursive && $cat_id_row){

            $rs = call_user_func_array(array($this,'getCatChildId'), array($cat_id_row, $recursive));
            $cat_id_row = array_merge($cat_id_row, $rs);
        }

        return $cat_id_row;
    }

}
